package com.renwei.yunlong.base;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.google.gson.Gson;
import com.renwei.yunlong.YunLongApplication;
import com.renwei.yunlong.activity.LoginActivity;
import com.renwei.yunlong.bean.LoginBean;
import com.renwei.yunlong.bean.ServerInfo;
import com.renwei.yunlong.bean.ServiceLoginBean;
import com.renwei.yunlong.event.AppInformationEvent;
import com.renwei.yunlong.event.MinePageRefreshEvent;
import com.renwei.yunlong.global.EventKey;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.ACache;
import com.renwei.yunlong.utils.AppManager;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.zyf.fwms.commonlibrary.utils.SharedPreUtil;

import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.util.HashMap;

import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import github.opensource.dialog.BeToastUtil;
import io.rong.imkit.RongIM;

/**
 * Created by wangqi on 2017/9/27.
 */

public class BaseActivity extends AppCompatActivity implements HttpTaskListener {

    protected Context mContext;
    protected Resources mResource;
    protected ACache mCache;
    protected ServiceLoginBean serviceLoginBean;
    protected LoginBean ownerBean;
    protected String companyType;
    private String TAG = "BaseActivity.class---";
    public ServerInfo info;
    protected boolean showInput = true;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 友盟推送
        PushAgent.getInstance(this).onAppStart();
        AppManager.getAppManager().addActivity(this);
        mContext = this;
        mCache = ACache.get(this);
        companyType = mCache.getAsString("companyType");
        YunLongApplication.setCompanyType(companyType);
        ownerBean = (LoginBean) mCache.getAsObject("loginBean");
        serviceLoginBean = (ServiceLoginBean) mCache.getAsObject("serviceLoginBean");
        mResource = getResources();
    }

    public void initApi() {
        info = DataSupport.where("current=?", "1").findFirst(ServerInfo.class);
        if (info != null && StringUtils.value(info.getAddress()).trim().length() > 1) {
            if (StringUtils.value(info.getPort()).length() <= 1) {
                Api.clean();//当IP地址中没有包含www。的时候时候代表是官网 不需要端口
                YunLongApplication.BASE_URL = StringUtils.value(info.getType() + info.getAddress());
            } else {
                Api.clean();//当IP地址中没有包含www。的时候时候代表是官网 不需要端口
                YunLongApplication.BASE_URL = StringUtils.value(info.getType() + info.getAddress() + ":" + info.getPort());
            }
        } else {
            initDefaultInfo();
        }
    }

    public void initDefaultInfo() {
        LitePal.getDatabase();
        ServerInfo info = new ServerInfo();
        info.setServerName("默认官网地址");
        info.setAddress(YunLongApplication.defaultLocalServerIP);
        info.setPort(YunLongApplication.defaultLocalServerPort);
        info.setType(YunLongApplication.defaultLocalHtp);
        info.setEditable("1");
        info.setCurrent("1");
        info.saveOrUpdate("serverName=?", StringUtils.value(info.getServerName()));
        initApi();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void refreshMcache() {
        ownerBean = (LoginBean) mCache.getAsObject("loginBean");
        serviceLoginBean = (ServiceLoginBean) mCache.getAsObject("serviceLoginBean");
    }

    public void clearMcache() {
        mCache.clear();
        companyType = "";
    }

    public String getCompanyCode() {
        String companyCode = "";
        if ("1".equals(companyType)) {
            companyCode = StringUtils.value(ownerBean.getRows().getCompany().getCompanyCode());
        } else if ("2".equals(companyType)) {
            companyCode = StringUtils.value(serviceLoginBean.getRows().getCompany().getCompanyCode());
        } else {
            LogUtil.e("公司数据错误");
            return "";
        }
        return companyCode;
    }

    public void exitApp() {
        try {

            SharedPreUtil.saveString(mContext, "default_company_type", companyType);
            if ("1".equals(companyType)) {
                SharedPreUtil.saveString(mContext, "owner_avatar", Api.$().OWNER_FILE_URL + ownerBean.getRows().getAvatar());
                SharedPreUtil.saveString(mContext, "owner_mobile", ownerBean.getRows().getUserName());
            } else {
                SharedPreUtil.saveString(mContext, "service_avatar", Api.$().SERVICE_FILE_URL + serviceLoginBean.getRows().getAvatar());
                SharedPreUtil.saveString(mContext, "service_mobile", serviceLoginBean.getRows().getUserName());
            }

            HashMap<String, String> map = new HashMap<>();
            map.put("deviceToken", YunLongApplication.getDeviceToken());
            map.put("phoneFlag", "0");
            if ("1".equals(companyType)) {
                map.put("userId", ownerBean.getRows().getEmployeeId());
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            } else {
                map.put("userId", serviceLoginBean.getRows().getEmployeeId());
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            }
            ServiceRequestManager.getManager().pushLogout(mContext, JsonMapUtil.mapToJson(map), null);
            // 退出融云
            RongIM.getInstance().logout();

            //清除通知栏
            NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            if (notiManager != null) {
                notiManager.cancelAll();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            EventBus.getDefault().post(new AppInformationEvent(AppInformationEvent.ExitApp));
            clearMcache();
            AppManager.getAppManager().finishAllActivity();
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    //显示信息toast
    protected void showCenterInfoMsg(String text) {
        if (!TextUtils.isEmpty(text)) {
            BeToastUtil.get().showCenterInfoMsg(this, text);
        }
    }


    //显示成功toast
    protected void showCenterSuccessMsg(String text) {
        if (!TextUtils.isEmpty(text)) {
            BeToastUtil.get().showCenterSuccessMsg(this, text);
        }
    }

    //显示错误snaker
    protected void showTopWrongMsg(String text) {
        if (!TextUtils.isEmpty(text)) {
            BeToastUtil.get().showTopWrongMsg(this, text);
        }
    }

    // 输入框的控制
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev) && showInput) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }


    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }


    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    protected void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
        ButterKnife.unbind(this);
    }

    public void refreshCompanyInfo() {
        ServiceRequestManager.getManager().QueryFirendCompany(this, getCompanyCode(), this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                ServiceLoginBean bean = new Gson().fromJson(result, ServiceLoginBean.class);
                if (bean.getMessage().getCode() == 200) {//登录成功
                    mCache.put("serviceLoginBean", bean);
                    mCache.put("companyType", "2");
                    refreshMcache();
                    EventBus.getDefault().post(new MinePageRefreshEvent(EventKey.UPDATE_COMPANY_INFO));
                }
                break;
            case 2:
                LoginBean loginBean = new Gson().fromJson(result, LoginBean.class);
                if (loginBean.getMessage().getCode() == 200) {//登录成功
                    mCache.put("loginBean", loginBean);
                    mCache.put("companyType", "1");
                    refreshMcache();
                    EventBus.getDefault().post(new MinePageRefreshEvent(EventKey.UPDATE_COMPANY_INFO));
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        LogUtil.e(TAG + "错误信息" + code);
    }
}
